<?php
    include("localConfig.php");
    class DB {
        private static $conn = null;
        public static function getConn(){
            global $conn;
            global $dataBaseName;
           if($conn == null){
                $conn = mysqli_connect("localhost", "root", "root");
            }
            if (!$conn->connect_error) {
                $conn->query('set names utf8');
                $conn->query("CREATE DATABASE IF NOT EXISTS ".$dataBaseName);
                $conn->query("use xphp");
            }else{
                die("连接失败:".$conn->connect_error);
            }
            return $conn;
        }
        /**
         * 通过对象字段获得最为匹配的数据表名
         * @param $data string "对象或对象列表"
         * @return int "表名"
         */
        public static function getTableNameByData($data){
            global  $dataBaseName;
            for($i=1;$i<10;$i++){
                if(is_array($data)){
                  if(array_key_exists("0", $data)){
                      $temp = $data[0];
                      if(is_array($temp) || is_object($temp)){
                          $data = $temp;
                      }
                  }
                }
            }
            if(!isset($data)){  //若$data为空则返回
                return false;
            }
            $sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '$dataBaseName'";
            $result= mysqli_query(self::getConn(),$sql);
            $tableList = mysqli_fetch_all($result);
            if($tableList){
                foreach ($tableList as $table){
                    $tableName = $table[0];
                    $sql = "SHOW COLUMNS FROM $tableName";   // 查询表的属性
                    $result= mysqli_query(self::getConn(),$sql);
                    $fields = "";
                    while($row = mysqli_fetch_assoc($result)) {
                        $fields .= $row["Field"];   //生成所有字段拼接的字符串
                    }
                    $flag = true;
                    foreach ($data as $key => $value) {
//                        echo $tableName."——".$fields."——".$key."——".(!strstr($fields,$key));
                        if(!strstr($fields,$key)){  //未匹配到包含的字符串
                            $flag = false;
                        }
                    }
                    if($flag){
                        return $tableName;
                    }
                }
            }
            return "";
        }
        /**
         * 处理sql语句
         * @param $sql string "sql语句"
         * @return string "select:返回对象或对象列表；insert:返回成功或者失败状态 ;update:返回影响行数"
         */
        public static function sqlQuery($sql){
            // select语句
            if(strpos($sql,"select ") !== false){
                $result = mysqli_query(self::getConn(),$sql);
                $array = [];
                while($row = mysqli_fetch_assoc($result)) {
                    $array[]=$row;
                }
                if(count($array)>0){  // 有查询结果
                    if(count($array)==1){
                        return json_decode(json_encode($array),FALSE)[0];  //返回对象类型
                    }else{
                        return $array;   //返回数组类型
                    }
                }else{  // 无查询结果
                    return null;
                }
            // insert语句
            }elseif(strpos($sql,"insert ") !== false){
                $result = mysqli_query(self::getConn(),$sql);
                if($result){
                    return true;
                }else{
                    return false;
                }
                // update语句
            }elseif(strpos($sql,"update ") !== false){
                $conn = self::getConn();
                $result = mysqli_query($conn,$sql);
                //对于update语句，一个大于0的整数表示所影响的记录行数；0表示没有受影响的记录；-1表示查询返回错误。
                return mysqli_affected_rows($conn);
            }
        }
        /**
         * 根据表名查询单个对象
         * @param $tableName string "表名"
         * @return object "单个对象"
         */

        public static function select_Object($tableName){
            $array = array();
            $result = mysqli_query(self::getConn(),"select * from ".$tableName);
            if(is_object($result)){
                $array = mysqli_fetch_assoc($result);
                return (object)$array;
            }else{
                return null;
            }
        }
        /**
         * 根据表名查询对象列表
         * @param $tableName string "表名"
         * @return array "对象列表"
         */
        public static function select_ObjectList($tableName){
            $array = array();
            $result = mysqli_query(self::getConn(),"select * from ".$tableName);
            if(is_object($result)){
                while($row = mysqli_fetch_assoc($result)) {
                    $array[]=$row;
                }
            }
           return $array;
        }
        /**
         * 插入单条对象数据
         * @param $data object "对应对象"
         * @param $tableName string "表名"
         * @return bool "成功:1，失败:0"
         */
        public static function insert_Object($data,$tableName = null){
            if(is_null($tableName)){
                $tableName = self::getTableNameByData($data);
            }
            //遍历数组，得到每一个字段和字段的值
            $keyList=$valueList="";
            foreach($data as $key=>$v) {
                //$key的值是每一个字段s一个字段所对应的值
                $keyList.=$key.',';
                $valueList.="'$v',";
            }
            $keyList=trim($keyList,',');
            $valueList=trim($valueList,',');   //判断数据是否为空
            $sql="insert into $tableName ($keyList) values ($valueList)";
            return mysqli_query(self::getConn(),$sql);
        }
        /**
         * 插入空对象数据
         * @param $tableName string "表名"
         * @return object "$object"
         */
        public static function create_Object($tableName){
            $sql = "SHOW COLUMNS FROM $tableName";   // 查询表的属性
            $result= mysqli_query(self::getConn(),$sql);
            $object = new stdClass();
            while($row = mysqli_fetch_assoc($result)) {
                $field = $row["Field"];
                $defaultValue = $row["Default"];
                $object->$field = $defaultValue;
            }
            $sql = "select max(id) as maxId FROM $tableName";
            $maxId = (int)(mysqli_fetch_assoc(mysqli_query(self::getConn(),$sql))["maxId"]) + 1;
            $object->id = $maxId;
            return $object;
        }

        //更新单条数据
        public static function update_Object($datas,$tableName=null){
            var_dump($datas);
            if(is_null($tableName)){
                $tableName = self::getTableNameByData($datas);
            }
            foreach ($datas as $k=>$data){
                if(is_array($data)){  // 若为对象类型
                    foreach($data as $key=>$value) {
                        echo $value;
                    }
                }else{
//                    if(is_array($data)){
//                        if(array_key_exists("0", $data)){
//                            $temp = $data[0];
//                            if(is_array($temp) || is_object($temp)){
//                                $data = $temp;
//                            }
//                        }
//                    }

                }

            }
//            mysqli_query(self::getConn(),$sql);
//            $rows = mysqli_affected_rows(getConn());
//            // mysqli_close(getConn());
//            return $rows;
        }
//
//        //删除单条数据
//        function delete_Object($sql){
//            mysqli_query(self::getConn(),$sql);
//            return mysqli_affected_rows(getConn());
//        }
    }
?>